public class HashBuck {

    static class Node{//内部类：代表 哈希桶
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    //负载因子
    public static final double LOAD_FACTOR = 0.75f;


    public HashBuck(){
        array = new Node[10];
    }

    //put
    public void put(int key,int val){
        int index = key % array.length;
        Node cur = array[index];
        while (cur!=null){
            if(cur.key == key){
                cur.key = val;
                return;
            }
            cur = cur.next;
        }
        //采用头插法:进行插入
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(calculateLoadFactor()>=LOAD_FACTOR){
            //扩容
            resize();
        }
    }

    //扩容，需要注意：  14%10 = 4  现在：14%20 = 14 了
    //如果要扩容：一定要记住 每个元素 都要进行重新的哈希计算
    private void resize() {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur!=null){
                Node curNext = cur.next;
                int index = cur.key%newArray.length;//找到了在新的数组的位置
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;

    }

    //计算负载因子
    public double calculateLoadFactor(){
        return usedSize*1.0/array.length;
    }

    //get
    public int get(int key){
        //如何放的，还如何找
        int index = key % array.length;
        Node cur = array[index];
        while (cur!=null){
            if(cur.key == key){
                return cur.val;
            }
        }
        return -1;
    }
}
